package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.dao.RedpacketMapper;
import com.wsd.smartcarwasher.domain.Redpacket;
import com.wsd.smartcarwasher.domain.RedpacketExample;
import com.wsd.smartcarwasher.util.GenerateAvatarImage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * Created by DaTangYun  YT on 2020/6/15 16:54
 */
@Service
public class RedPacketService {

    @Resource
    RedpacketMapper redpacketMapper;
    @Resource
    WxService wxService;
    public int createPacket(Redpacket redpacket) {
        return redpacketMapper.insert(redpacket);
    }
    public int deletePacket(int id) {
        RedpacketExample example=new RedpacketExample();
        RedpacketExample.Criteria criteria=example.createCriteria();
        Redpacket redpacket=new Redpacket();
        redpacket.setpacketId(id);
        redpacket.setStatus(false);
        return redpacketMapper.updateByPrimaryKey(redpacket);
    }
    public int updatePacket(Redpacket redpacket) {
        return redpacketMapper.updateByPrimaryKey(redpacket);
    }
    public Redpacket getPacket(int packetId){return redpacketMapper.selectByPrimaryKey(packetId);}
    public List<Redpacket> showPacket() {
        RedpacketExample example=new RedpacketExample();
        RedpacketExample.Criteria criteria=example.createCriteria();
        criteria.andStatusEqualTo(true);
        List<Redpacket> redpacketList = redpacketMapper.selectByExample(example);
        if (redpacketList.isEmpty()) {
            return Collections.emptyList();
        }
        return redpacketList;
    }

    public String generateRedPacketWxCode(Redpacket redpacket) throws IOException {
        String fileName = "redpacket_wxCode_" + System.currentTimeMillis() +"_"+redpacket.getpacketId()+ ".jpeg";
        String wxCodeUrl = this.wxService.getWxACodeFromWx("r=" + redpacket.getpacketId()+"&t=3", fileName, "pages/index/index");
        if (StringUtils.isNotBlank(wxCodeUrl)) {

            wxCodeUrl= GenerateAvatarImage.generateImage(wxCodeUrl);
            redpacket.setCode(Constant.DOMAIN+wxCodeUrl);
            int changeRow = this.redpacketMapper.updateByPrimaryKey(redpacket);
            if (changeRow == 0) {
               System.out.println(String.format("update machine wxCode fail, couponId = %s, wxCodeUrl = %s", redpacket.getpacketId(), wxCodeUrl));
                return null;
            } else {
                return wxCodeUrl;
            }
        } else {
            return null;
        }
    }

}
